<template>
  <div>
    <div v-for="(value,key) in apiData">
      <n-divider />
      <n-space item-style="display: flex;" vertical>
        <p>{{ key }}</p>
        <n-button-group size="tiny">
          <n-button size="tiny" @click="handleCheckedChange({key, checked:true})">全部选中</n-button>
          <n-button size="tiny" @click="handleCheckedChange({key, checked:false})">取消选择</n-button>
        </n-button-group>


        <n-space item-style="display: flex;" align="center">
          <n-checkbox-group v-model:value="checkedRef[key]" @update:value="handleUpdateValue">
            <n-checkbox v-for="item in value" :value="item.apiName" :label="item.apiName" />
          </n-checkbox-group>
        </n-space>
      </n-space>
    </div>
  </div>
</template>
<script lang="ts">
import { reactive, ref, unref } from "vue";
import { FormInst } from "naive-ui";

export default {
  props: {
    apiData: {
      type: [Object],
      default: () => {
        return {};
      }
    }
  },
  setup(props) {
    const formInstance = ref<FormInst | null>(null);
    const { apiData } = unref(props);
    const formData = ref<any>({
      file: 0,
      url: "",
      text: "",
      fileName: "暂未选择文件"
    });
    const checkedRef = ref(reactive({}));
    const apiList = {};
    for (const grop in apiData) {
      const t: [] = apiData[grop];
      for (let i = 0; i < t.length; i++) {
        apiList[t[i]["apiName"]] = t[i];
      }
    }
    const doSubmit = async () => {
      const tempList = [];
      for (const key in checkedRef.value) {
        const tt: [] = checkedRef.value[key];
        tempList.push(...tt);
      }
      const resultList = [];
      for (const key of tempList) {
        resultList.push(apiList[key]);
      }
      return {
        code: 200,
        msg: "选择接口成功",
        data: resultList
      };
    };
    const handleUpdateValue = async (value) => {
      checkedRef.value[value] = reactive(value);
    };
    const handleCheckedChange = async (value) => {
      console.log(value);
      const { key, checked } = value;
      if (checked) {
        checkedRef.value[key] = reactive(apiData[key].map(it => {
          return it.apiName;
        }));
      } else {
        checkedRef.value[key] = reactive([]);
      }
    };
    return {
      checkedRef,
      handleCheckedChange,
      handleUpdateValue,
      formInstance,
      formData,
      doSubmit
    };
  }
};
</script>
